﻿using SelfManagement.Mvc.Helper;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using SelfManagement.Utility.Extensions;
using System.Web;
using System.Web.Mvc;

namespace SelfManagement.Mvc.Helper
{
    public static class HtmlHelperExtensions
    {
        /// <summary>
        /// html拓展 :用于获取枚举类型的中文描述
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="value">枚举值</param>
        /// <returns></returns>
        public static HtmlString EnumDecription(this HtmlHelper helper, Enum value)
        {
            Type enumType = value.GetType();
            string name = Enum.GetName(enumType, value);

            if(name != null)
            {
                FieldInfo fieldInfo = enumType.GetField(name);
                if(fieldInfo != null)
                {
                    DescriptionAttribute attr = Attribute.GetCustomAttribute(fieldInfo,
                        typeof(DescriptionAttribute), false) as DescriptionAttribute;
                    if(attr != null)
                    {
                        name = attr.Description;
                    }
                }
            }
            return new HtmlString(name);
        }

        /// <summary>
        /// html拓展 :用于获取多个枚举值的中文描述
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="enumType">枚举类型</param>
        /// <param name="namesStr">枚举字段的字符串</param>
        /// <param name="split">描述的分隔符</param>
        /// <returns></returns>
        public static HtmlString EnumsDescription(this HtmlHelper helper, Type enumType, string namesStr, string split = "|")
        {
            var items = SelectListItemsHelper.FromEnum(enumType);
            var names = namesStr.ToList();
            var texts = items.Where(i => names.Contains(i.Value)).Select(i => i.Text).ToList();
            return new HtmlString(string.Join(split, texts));
        }
    }
}
